const express = require('express')
const WebSocket = require('ws')
const http = require('http')
const os = require('os')
const open = require('opn')
const cors = require('cors') // 需要先安装：npm install cors

const app = express()
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })

// 开发环境CORS配置 - 允许本地和局域网访问
const corsOptions = {
  origin: function (origin, callback) {
    // 开发环境允许所有来源（包括React Native等移动应用）
    console.log('CORS origin:', origin || 'no-origin (mobile app)')
    callback(null, true)
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
}

app.use(cors(corsOptions))

// 静态文件服务
app.use(express.static('public'))
app.use('/docs', express.static('docs'))
app.use('/examples', express.static('examples'))
app.use(express.json())

function getServerIP() {
  const interfaces = os.networkInterfaces()
  for (const iface of Object.values(interfaces)) {
    for (const alias of iface) {
      if (alias.family === 'IPv4' && !alias.internal) {
        return alias.address
      }
    }
  }
  return 'localhost'
}
const PORT = process.env.PORT || 3000

// 添加服务器错误处理
server.on('error', (error) => {
  if (error.code === 'EADDRINUSE') {
    console.log(`❌ Port ${PORT} is already in use. Please try a different port or stop the existing server.`)
    console.log(`💡 To kill existing processes: lsof -ti:${PORT} | xargs kill -9`)
  } else {
    console.error('Server error:', error)
  }
})

server.listen(PORT, '0.0.0.0', async () => {
  const serverIP = getServerIP()
  console.log(`\n🚀 Universal Debug Logger Server`)
  console.log(`📍 HTTP Server: http://${serverIP}:${PORT}`)
  console.log(`🔌 WebSocket Server: ws://${serverIP}:${PORT}`)
  console.log(`📖 Documentation: http://${serverIP}:${PORT}/docs/`)
  console.log(`🎮 Debug Panel: http://${serverIP}:${PORT}/debug-panel.html`)
  console.log(`🧪 Test Page: http://${serverIP}:${PORT}/examples/test.html`)
  console.log(`📋 Legacy Panel: http://${serverIP}:${PORT}/index.html`)

  // 默认打开文档网站
  const docsURL = `http://${serverIP}:${PORT}/docs/`
  open(docsURL)
})

let logMessages = [] // 用于存储所有日志消息的数组

// 统一的消息处理函数
function handleLogMessage(messageData, source) {
  const { type, timestamp, data } = messageData

  // 处理清空消息
  if (type === 'clear') {
    logMessages = []

    // 广播清空消息到所有客户端
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({ type: 'clear' }))
      }
    })

    return { success: true, message: 'Logs cleared' }
  }

  // 处理日志和网络消息
  if (type === 'log' || type === 'network') {
    const logEntry = {
      type,
      timestamp: timestamp,
      data: data,
      id: data.id || Date.now() + Math.random(),
    }

    logMessages.push(logEntry)

    // 限制消息数量
    if (logMessages.length > 2000) {
      logMessages = logMessages.slice(-2000)
    }

    // 按时间戳排序
    logMessages.sort((a, b) => {
      const timestampA = parseInt(a.timestamp)
      const timestampB = parseInt(b.timestamp)
      return timestampA - timestampB
    })

    // 广播新消息到所有WebSocket客户端
    const messageToSend = { type, timestamp, data }
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN && client !== source) {
        client.send(JSON.stringify(messageToSend))
      }
    })

    return { success: true, message: 'Message received' }
  }

  return { success: false, message: 'Unknown message type' }
}

// WebSocket连接处理
wss.on('connection', function connection(ws, req) {
  const clientIP = req.socket.remoteAddress
  console.log(`🔗 WebSocket client connected from ${clientIP}`)

  // 发送连接确认
  ws.send(
    JSON.stringify({
      type: 'connection',
      message: 'Connected to debug server',
      timestamp: Date.now().toString(),
    }),
  )

  ws.on('message', function incoming(message) {
    try {
      const data = JSON.parse(message)
      console.log('📨 WebSocket received:', data.type || 'unknown')

      // 处理WebSocket消息（与HTTP API相同的逻辑）
      handleLogMessage(data, ws)
    } catch (error) {
      console.warn('WebSocket message parse error:', error.message)
    }
  })

  ws.on('close', function () {
    console.log(`🔌 WebSocket client disconnected from ${clientIP}`)
  })

  ws.on('error', function (error) {
    console.warn('WebSocket client error:', error.message)
  })
})

app.post('/api/log', (req, res) => {
  try {
    console.log('📡 HTTP API received:', req.body.type || 'unknown')

    // 使用统一的消息处理函数
    const result = handleLogMessage(req.body)

    if (result.success) {
      res.status(200).send({ msg: result.message })
    } else {
      // 兼容旧格式
      const { message, timestamp } = req.body
      if (message) {
        if (clearMessage(message)) {
          const clearResult = handleLogMessage({ type: 'clear' })
          return res.status(200).send({ msg: clearResult.message })
        }

        const legacyLog = {
          type: 'log',
          timestamp: timestamp || Date.now().toString(),
          data: {
            id: Date.now() + Math.random(),
            timestamp: timestamp || Date.now().toString(),
            level: 'log',
            message: Array.isArray(message) ? message : [message],
          },
        }

        const legacyResult = handleLogMessage(legacyLog)
        return res.status(200).send({ msg: legacyResult.message })
      }

      res.status(400).send({ error: 'Invalid message format' })
    }
  } catch (error) {
    console.error('Error processing log message:', error)
    res.status(500).send({ error: 'Internal server error' })
  }
})

app.options('/api/log', cors(corsOptions)) // 为特定路径处理 OPTIONS 请求

function clearMessage(message = []) {
  return message[0] === 'clear'
}
function concatenateMessages(timestamp, messages) {
  let output = timestamp + ': '

  for (let message of messages) {
    if (typeof message === 'object') {
      output += JSON.stringify(message) + '      '
    } else {
      output += message + '      '
    }
  }
  return output.trim() // 去除末尾的空格
}
